package com.gjun.struts.action;

import java.awt.Font;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.struts2.ServletActionContext;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import com.gjun.struts.bean.GjunMonthShopBean;
import com.gjun.struts.resource.MonthReportDAOIf;

public class MonthReportAction {

	private String result; 

	private String type;

	private String province;

	private String city;

	private String shop;

	private String reportmonth;

	private String orderBy;

	private String limit;

	private String view;

	private String reportmonth2;

	private String showothers;

	private MonthReportDAOIf monthReportDAO;

	public String getShowothers() {
		return showothers;
	}

	public void setShowothers(String showothers) {
		this.showothers = showothers;
	}

	public MonthReportDAOIf getMonthReportDAO() {
		return monthReportDAO;
	}

	public void setMonthReportDAO(MonthReportDAOIf monthReportDAO) {
		this.monthReportDAO = monthReportDAO;
	}

	public String getLimit() {
		return limit;
	}

	public void setLimit(String limit) {
		this.limit = limit;
	}

	public String getOrderBy() {
		return orderBy;
	}

	public void setOrderBy(String orderBy) {
		this.orderBy = orderBy;
	}

	public String getReportmonth() {
		return reportmonth;
	}

	public void setReportmonth(String reportmonth) {
		this.reportmonth = reportmonth;
	}

	public String getReportmonth2() {
		return reportmonth2;
	}

	public void setReportmonth2(String reportmonth2) {
		this.reportmonth2 = reportmonth2;
	}

	public String getShop() {
		return shop;
	}

	public void setShop(String shop) {
		this.shop = shop;
	}

	public String getView() {
		return view;
	}

	public void setView(String view) {
		this.view = view;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String decode(String str) {
		try {
			System.out.println("str:   " + str);
			// return new String(str.getBytes("GBK"),"UTF-8");
			return URLEncoder.encode(str, "GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return str;
		}
	}

	public String serviceMonth(String month) {
		if (month == null || month.trim().length() < 1)
			return month;
		if (month.substring(month.length() - 2, month.length() - 1).equals("0")) {

			month = month.substring(0, month.length() - 2)
					+ month.substring(month.length() - 1);

		}
		return month;
	}

	public static void main(String[] args) {
		MonthReportAction a = new MonthReportAction();
		System.out.println(a.serviceMonth("2010-05"));
	}

	public String execute() {
//		System.out.println("省份dd:  " + province);
//		System.out.println("城市dd:  " + city);
//		System.out.println("店铺ddasdasdaqweqw:  " + shop);
//		System.out.println("柱形图".equals(view));
//		System.out.println("月份1:  " + reportmonth);
//		System.out.println("月份2:  " + reportmonth2);
//		System.out.println("排序方式:  " + orderBy);
//		System.out.println("limit:  " + limit);
//		System.out.println("view==============:  " + view);
//		System.out.println("dao:  " + monthReportDAO);
//		System.out.println("showothers:  " + showothers);
        result="";
        	
        	
		// 表示没有选择高级选项,那么查询条件不需要包含复杂条件

		Map<String, List<GjunMonthShopBean>> reports = null;
		if (showothers == null) {
			reports = monthReportDAO.loadMonthDetails(province, city, shop,
					serviceMonth(reportmonth), null, null, null);
		} else {
			reports = monthReportDAO.loadMonthDetails(province, city, shop,
					serviceMonth(reportmonth), orderBy, limit,
					serviceMonth(reportmonth2));
			
		}
		
		String path = ServletActionContext.getRequest().getRealPath("/report");

		if ("饼状图".equals(view)) {
			System.out.println("生成饼状图");
			/*
			 * 饼图使用DefaultPieDataset为图表提供数据。
			 */
			result += reports.size()+"#";
			Set<Map.Entry<String, List<GjunMonthShopBean>>> entry = reports
					.entrySet();
			for (Map.Entry<String, List<GjunMonthShopBean>> report : entry) {
				System.out.println("数据........................:   "+report.getKey());
				DefaultPieDataset dataset = new DefaultPieDataset();
				/*
				 * // 第一个参数是数据的名称，第二个数据是数据的值。 dataset.setValue("jfree", 100);
				 * dataset.setValue("chart", 200); dataset.setValue("struts",
				 * 300); dataset.setValue("hibernate", 100);
				 */
				System.out.println("11111111111111");
				for (GjunMonthShopBean details : report.getValue()) {
					System.out.println("2222222222222:  "
							+ details.getStoreCode() + "\t"
							+ details.getMonth().getTotalincome());
					dataset.setValue(details.getStoreCode() + "", details
							.getMonth().getTotalincome());
				}
				JFreeChart chart = ChartFactory.createPieChart(report.getKey()
						+ "月报表数据", dataset, true, false, false);

				// 炸开的饼图调用PiePlot中的setExplodePercent方法来实现这一功能。
				PiePlot pp = (PiePlot) chart.getPlot();
				pp.setExplodePercent("jfree", 0.3);
				pp.setNoDataMessage("无数据显示");

				StandardPieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator(
						("{0}={1}({2})"), NumberFormat.getNumberInstance(),
						new DecimalFormat("0.00%"));
				pp.setLabelGenerator(generator);

				FileOutputStream fos = null;

				try {

					String timer = nowTime(new Date());
					fos = new FileOutputStream(path + "\\" + timer+report.getKey()
							+ ".png");
					result += ServletActionContext.getRequest().getContextPath()
							+ "/report/" + timer+report.getKey() + ".png#";
					ChartUtilities.writeChartAsPNG(fos, chart, 600, 450);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
				
			}
			System.out.println("饼状图result:  "+result);
		} else if("柱形图".equals(view)){

			result += reports.size()+"#";
			final Font CHART_FONT = new Font("宋体", 12, 12);
			Set<Map.Entry<String, List<GjunMonthShopBean>>> entry = reports
					.entrySet();
			for (Map.Entry<String, List<GjunMonthShopBean>> report : entry) {
				DefaultCategoryDataset dataset = new DefaultCategoryDataset();
				
				for (GjunMonthShopBean details : report.getValue()) {
					
					dataset.addValue(details.getMonth().getTotalincome(),details.getMonth()
							.getTotalincome(),details.getStoreCode() );
					// dataset.addValue(150, "ten", "chart");
				}
				
				JFreeChart chart = ChartFactory.createBarChart3D(
						report.getKey()
						+ "月报表数据",                     // 标题
					       "分店",                      // x轴名称
					       "销售额",                     // y轴名称
					       dataset,             // 数据
					       PlotOrientation.VERTICAL,   // 垂直柱状图,PlotOrientation.HORIZONTAL水平柱状图
					       true,                       // 是否使用legend
					       false,                      // 是否使用tooltip
					       false                       // 是否使用url链接
					          );
					  // 设置中文
					  // JfreeChinese.setChineseForXY(chart);
				
				FileOutputStream fos = null;

				try {
                    String timer = nowTime(new Date());
					fos = new FileOutputStream(path + "\\" + timer+report.getKey()
							+ ".png");
					result += ServletActionContext.getRequest().getContextPath()
							+ "/report/" + timer+report.getKey() + ".png#";
					ChartUtilities.writeChartAsPNG(fos, chart, 600, 450);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			//result += reports.size();
			System.out.println("柱形图result:  "+result);

		}else{
			System.out.println("生成普通数据");
		}

		return "success";
	}
	
	public String nowTime(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		return sdf.format(date);
	}
}
